﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Common;
using Lamex.Library.CommonClass;
using Lamex.Interface;
using System.Timers;
using Lamex.NC.BLL;
using Lamex.NC.Model;
using Lamex.Base;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;
using DevExpress.Utils;
using DevExpress.XtraEditors.Filtering.Templates;
using System.Xml;
using System.IO;
using System.Security.AccessControl;
using System.Runtime.InteropServices;
using DevExpress.Xpo.DB.Helpers;

namespace Lamex.mNC.UI
{
    public partial class frmNC_Convert_Processing_Follow : frmBaseChild
    {
        #region""
        IntPtr handle;
        [DllImport("user32.dll", SetLastError = true)]

        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 0x10000000;
        const Int32 WS_BORDER = (Int32)0x00800000L;
        const Int32 WS_THICKFRAME = (Int32)0x00040000L;
        const Int32 SWP_NOMOVE = 0x0002;
        const Int32 SWP_NOSIZE = 0x0001;
        const Int32 SWP_NOZORDER = 0x0004;
        const Int32 SWP_FRAMECHANGED = 0x0020;
        const Int32 SW_MAXIMIZE = 3;
        IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        //[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
        //private static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong);
        [DllImport("user32", EntryPoint = "SetWindowLong", SetLastError = true)]
        private static extern uint SetWindowLong(
        IntPtr hwnd,
        int nIndex,
        int dwNewLong
        );
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        static extern Int32 SetWindowPos(IntPtr hWnd,
   IntPtr hWndInsertAfter,
   Int32 X,
   Int32 Y,
   Int32 cx,
   Int32 cy,
   UInt32 uFlags
 );
        #endregion
        System.Timers.Timer t=null;
        List<NC_Convert_ProcessRecordInfo> lst = new List<NC_Convert_ProcessRecordInfo>();
        List<NC_Convert_ProcessRecordInfo> noLst = new List<NC_Convert_ProcessRecordInfo>();
        public frmNC_Convert_Processing_Follow()
        {
            InitializeComponent();
        }

        private void frmNC_Convert_Processing_Follow_Resize(object sender, EventArgs e)
        {
            //splitContainerControl1.SplitterPosition = this.Width - 210;
        }

        private void frmNC_Convert_Processing_Follow_Load(object sender, EventArgs e)
        {
            base.InitButtons();//初始化标准功能
            string CurUser = Lamex.Common.Loginer.CurrentUser.Account;

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ColumnAutoWidth = false;

            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);//表格设置-右键功能   
            // DevStyle.SetSummaryGridViewLayout(gridView1);//是否显示底部阴影条
            //DevStyle.SetDetailGridViewLayout(gridView1);  //是否显示筛选项 
            //create record datable 
            
            //update data to SJ
            t = new System.Timers.Timer(1000*60*2);
            t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_UP);
            t.AutoReset = true;
            t.Enabled = true;
            t.Start();
            cboxPlanning_Engineer.Properties.Items.Clear();
            DataSet ds = Lamex.Base.BaseBuildSql.GetDataSetBySql(" select UserName from NC_Convert_StaffPlan ;select FIELD_VALUE_OPTION from Sys_ControlValueOption where FIELD_NAME='NC_STATE' ");
            foreach(DataRow dr in ds.Tables[0].Rows)
            {
                cboxPlanning_Engineer.Properties.Items.Add(dr["UserName"].ToString());
            }
            datePlanning_Status.Properties.Items.Clear();
            foreach (DataRow dr in ds.Tables[1].Rows)
            {
                string[] strArray = dr["FIELD_VALUE_OPTION"].ToString().Split(',');
                foreach(string s in strArray)
                    datePlanning_Status.Properties.Items.Add(s);
            }
        }

        private void sbtnRefresh_Click(object sender, EventArgs e)
        {
           

            
        }

        
        private void SetGridViewDateType2SecondLevel(DevExpress.XtraGrid.Views.Grid.GridView gv)
        {

            //setting datatime to show UI
            gv.Columns.Where(x => x.ColumnType.Name == "DateTime").ToList().ForEach(x => x.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss");
            List<GridColumn> gcList = gv.Columns.Where(x => x.ColumnType.Name == "DateTime").ToList();
            RepositoryItemDateEdit nRide = new RepositoryItemDateEdit();
            nRide.CalendarView = CalendarView.Vista;
            nRide.CalendarTimeEditing = DefaultBoolean.True;
            nRide.DisplayFormat.FormatString = "G";
            nRide.DisplayFormat.FormatType = FormatType.DateTime;
            nRide.EditFormat.FormatString = "G";
            nRide.EditFormat.FormatType = FormatType.DateTime;
            nRide.EditMask = "G";
            gv.Columns.Where(x => x.ColumnType.Name == "DateTime").ToList().ForEach(x => x.ColumnEdit = nRide);
        }
        private void gridView1_Click(object sender, EventArgs e)
        {
            //TO DO
            //右侧vGridControl1显示当前行数据
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            int iRow = gridView1.FocusedRowHandle;

            string CurCellValue = gridView1.FocusedValue.ToString();

            string NC_TYPE = gridView1.GetRowCellDisplayText(iRow, "转码类别").ToString();

            string PART_NO = gridView1.GetRowCellDisplayText(iRow, "部件编号").ToString();
            string PART_DESC = gridView1.GetRowCellDisplayText(iRow, "部件描述").ToString();
            string GRAIN = gridView1.GetRowCellDisplayText(iRow, "木纹方向").ToString();
            string THICK = gridView1.GetRowCellDisplayText(iRow, "部件厚度").ToString();

            string PLANNING_ENGINEER = gridView1.GetRowCellDisplayText(iRow, "计划转码").ToString();
            string PLANNING_DONETIME = gridView1.GetRowCellDisplayText(iRow, "计划完成").ToString();

            string CONVERTED_TIME = gridView1.GetRowCellDisplayText(iRow, "转码完成").ToString();
            string CHECHED_TIME = gridView1.GetRowCellDisplayText(iRow, "审核完成").ToString();
            string RELEASED_TIME = gridView1.GetRowCellDisplayText(iRow, "上载完成").ToString();

            string LOCKED_USER = gridView1.GetRowCellDisplayText(iRow, "锁定用户").ToString();
            string ISSUE_NO = gridView1.GetRowCellDisplayText(iRow, "问题单号").ToString();

            //if (LOCKED_USER.Trim().Length > 0)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("当前记录正在被【" + LOCKED_USER + "】锁定中！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            //if (!string.IsNullOrEmpty(RELEASED_TIME.Trim()))
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("当前记录已上载，不允许编辑！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            //#region 根据用户操作进行窗体跳转

            //if (string.IsNullOrEmpty(CurCellValue))
            //{
            //    //??????
            //}

            ////跳转到排期逻辑
            //if (gridView1.FocusedColumn.FieldName == "计划转码" || gridView1.FocusedColumn.FieldName == "计划完成")
            //{
            //    MessageBox.Show("跳转到排期逻辑");
            //}

            ////跳转到NC转码窗体
            //if (gridView1.FocusedColumn.FieldName == "转码完成")
            //{
            //    if (string.IsNullOrEmpty(CONVERTED_TIME))
            //    {
            //        //打开窗体，并将部件编号、部件描述、木纹方向、部件厚度传递过去
            //        switch (NC_TYPE)
            //        {
            //            case "DESK_SJR":
            //                frmNC_Convert_DKSJR_Processing form1 = new frmNC_Convert_DKSJR_Processing(PART_NO);
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form1, "menuNC_Convert_Processing_DKSJR");
            //                form1.DoView(null);
            //                break;
            //            case "DESK_STD":
            //                frmNC_Convert_DKSTD_Processing form2 = new frmNC_Convert_DKSTD_Processing();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form2, "menuNC_Convert_Processing_DKstd");
            //                form2.DoView(null);
            //                break;
            //            case "PANEL_SJR":
            //                frmNC_Convert_PN_AL_SJR form3 = new frmNC_Convert_PN_AL_SJR();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form3, "frmNC_Convert_PNAL_SJR");
            //                form3.DoView(null);
            //                break;
            //            case "PANEL_STD":
            //                frmNC_Convert_PN_AL_STD form4 = new frmNC_Convert_PN_AL_STD();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form4, "frmNC_Convert_PNAL_STD");
            //                form4.DoView(null);
            //                break;
            //            default:
            //                break;
            //        }
            //    }

            //    //frmNC_Convert_DKSJR_Processing form = new frmNC_Convert_DKSJR_Processing();
            //}

            ////跳转到NC审核窗体
            //if (gridView1.FocusedColumn.FieldName == "审核完成")
            //{
            //    if (string.IsNullOrEmpty(CHECHED_TIME))
            //    {
            //        //打开窗体，并将部件编号、部件描述、木纹方向、部件厚度传递过去
            //        switch (NC_TYPE)
            //        {
            //            case "DESK_SJR":
            //                frmNC_Convert_DKSJR_Checking form1 = new frmNC_Convert_DKSJR_Checking();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form1, "frmNC_Convert_DKSJR_Checking");
            //                form1.DoView(null);
            //                break;
            //            case "DESK_STD":
            //                frmNC_Convert_DKSTD_Checking form2 = new frmNC_Convert_DKSTD_Checking();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form2, "frmNC_Convert_DKSTD_Checking");
            //                form2.DoView(null);
            //                break;
            //            case "PANEL_SJR":
            //                frmNC_Convert_PN_AL_SJR form3 = new frmNC_Convert_PN_AL_SJR();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form3, "frmNC_Convert_PNAL_SJR");
            //                form3.DoView(null);
            //                break;
            //            case "PANEL_STD":
            //                frmNC_Convert_PN_AL_STD form4 = new frmNC_Convert_PN_AL_STD();
            //                MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form4, "frmNC_Convert_PNAL_STD");
            //                form4.DoView(null);
            //                break;
            //            default:
            //                break;
            //        }
            //    }
            //}

            ////跳转到NC代码上载窗体
            //if (gridView1.FocusedColumn.FieldName == "上载完成")
            //{
            //    //打开窗体，并将所有未上载（释放）记录传递过去
            //    frmNC_Convert_Code_Releasing form = new frmNC_Convert_Code_Releasing();
            //    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, "menuNC_Convert_Uploading");
            //    form.DoView(null);
            //}

            ////跳转到NC问题记录窗体
            //if (gridView1.FocusedColumn.FieldName == "问题单号")
            //{
            //    if (string.IsNullOrEmpty(ISSUE_NO))
            //    {
            //        //打开窗体
            //        frmNC_Convert_Issue_Follow form = new frmNC_Convert_Issue_Follow();
            //        MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form, "menuNC_Issue_Record");
            //        form.DoView(null);
            //    }
            //}

            //#endregion
        }

        #region 选项区显示/隐藏、表数据导出/打印、表复制设置、表页脚设置、基础配置窗体跳转

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl_Top.Height = 0;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelControl_Top.Height = 60;
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView1);
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToPrint(gridControl1, this.Text);
        }

        //gridView仅复制单元格内容，复制选中行焦点单元格的值
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gridView1.GetFocusedRowCellValue(gridView1.FocusedColumn));
                e.Handled = true;
            }

            //或设置属性
            //optionBehavior - CopyToClipboardWithColumnHeader = false;
            //optionSelection - MultiSelectMode = CellSelect;
        }

        //GRIDVIEW页脚汇总设置
        private void TotalSum()
        {
            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "合计：";
            if (gridView1.Columns.Contains(gridView1.Columns[1]))
            {
                gridView1.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns[1].SummaryItem.DisplayFormat = "{0:N}";
                // this.gridView1.Columns[1].Width = 80;
            }
            if (gridView1.Columns.Contains(gridView1.Columns[2]))
            {
                gridView1.Columns[2].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns[2].SummaryItem.DisplayFormat = "{0:N}";
                //this.gridView1.Columns[2].Width = 80;
            }
        }

        //基础配置窗体跳转
        private void labelGoto_Click(object sender, EventArgs e)
        {
            Loginer.CurrentUser.FunctionId = "menuSCH_Owed_QTY_List";
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("View_OP_Follow_Owed_QTY", 1, false, false), sender as ToolStripMenuItem);
        }

        #endregion

        #region 实例化标准功能

        public override void DoView(IButtonInfo sender)
        {
            string strSql = "";
            string strWhere = "";
            //        strSql = @"SELECT a.NC_TYPE AS 转码类别,a.JOB_NO AS 工作单号,a.MODEL_NO AS 产品型号,
            //            a.PART_NO AS 部件编号,a.DWG_NO AS 图纸编号,a.PART_DESC AS 部件描述,a.GRAIN AS 木纹方向,
            //a.THICK AS 部件厚度,a.CREATED_USER AS 号码创建,
            //            a.IMPORT_TIME AS 导入时间,b.PLANNING_ENGINEER AS 计划转码,b.PLANNING_DONETIME AS 计划完成,b.CONVERTED_ENGINEER as 实际转码人,
            //            b.CONVERTED_TIME AS 转码完成,b.CHECHED_TIME AS 审核完成,b.RELEASED_TIME AS 上载完成,
            //            b.LOCKED_USER AS 锁定用户,b.ISSUE_NO AS 问题单号,a.MODEL_NO as 模型编号
            //            FROM NC_Convert_TaskList AS a
            //            INNER JOIN NC_Convert_ProcessRecord AS b
            //            ON a.PART_NO=b.PART_NO AND b.RELEASED_TIME IS NULL where PLANNING_ENGINEER!='admin'";

            strSql = @"SELECT a.NC_TYPE AS 转码类别,a.JOB_NO AS 工作单号,a.MODEL_NO AS 产品型号,
                a.PART_NO AS 部件编号,a.DWG_NO AS 图纸编号,a.PART_DESC AS 部件描述,a.GRAIN AS 木纹方向,
				a.THICK AS 部件厚度,a.CREATED_USER AS 号码创建,
                b.PLANNING_START_TIME AS 开始时间,b.PLANNING_ENGINEER AS 计划转码,b.PLANNING_DONETIME AS 计划完成,b.CONVERTED_ENGINEER as 实际转码人,
                b.CONVERTED_TIME AS 转码完成,b.CHECHED_ENGINEER as 审核人,b.CHECHED_TIME AS 审核完成,b.RELEASED_TIME AS 上载完成,
                b.LOCKED_USER AS 锁定用户,b.ISSUE_NO AS 问题单号,a.MODEL_NO as 模型编号,
				case when  ISNULL(c.ROUTING_CODE,'')!='' then 'Y' else 'N' end 工艺状态,
                b.DWG_NO 图纸号,b.NC_STATE NC状态
                FROM NC_Convert_TaskList AS a
                INNER JOIN NC_Convert_ProcessRecord AS b
                ON a.PART_NO=b.PART_NO AND b.RELEASED_TIME IS NULL 
			   left join (select a.PART_NO, b.* from IE_Part_Routing a 
join IE_Routing_Combination b on a.GROUP_CODE = b.GROUP_CODE) c on c.PART_NO=a.PART_NO
				where PLANNING_ENGINEER!='admin'";
            if (!string.IsNullOrEmpty(cboxNC_Type.Text))
            {
                strWhere += " and  a.NC_TYPE='" + cboxNC_Type.Text + "'";
            }
            if (!string.IsNullOrEmpty(txtSJR_No.Text))
            {
                strWhere += " and  a.JOB_NO='" + txtSJR_No.Text + "'";
            }
            if (!string.IsNullOrEmpty(cboxPlanning_Engineer.Text))
            {
                strWhere += " and  b.PLANNING_ENGINEER='" + cboxPlanning_Engineer.Text + "'";
            }
            if (!string.IsNullOrEmpty(txtPartNo.Text))
            {
                strWhere += " and  a.PART_NO='" + txtPartNo.Text + "'";
            }
            if (!string.IsNullOrEmpty(datePlanning_Status.Text))
            {
                strWhere += " and  b.NC_STATE='" + datePlanning_Status.Text + "'";
            }
            if(chkHide.Checked==true)
                strWhere += " and   isnull(b.NC_STATE,'')!='已审核'";
            strSql += strWhere;

            DataTable dt = null;
            gridControl1.DataSource = null;
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            if (dt.Rows.Count > 0)
            {
                gridControl1.DataSource = dt;

                SetGridViewDateType2SecondLevel(gridView1);
                frmGridViewCust.RegisterGrid(gridView1);
                gridView1.BestFitColumns();
                //TotalSum();//统计求和
            }
            base.DoView(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            导出ToolStripMenuItem_Click(null, null);
            base.DoExport(sender);
        }

        public override void DoPrint(IButtonInfo sender)
        {
            打印ToolStripMenuItem_Click(null, null);
            base.DoPrint(sender);
        }

        #endregion
        /// <summary>
        /// 5 minute update SJ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_UP(object sender,ElapsedEventArgs e)
        {
            lst.Clear();
            noLst.Clear();
            DataTable dtTaskList = Lamex.Base.BaseBuildSql.GetDataTableBySql(@"SELECT * from NC_Convert_TaskList where PART_NO not in(
                                                      select PART_NO from NC_Convert_ProcessRecord  ) and  ISNULL(PLAN_FLAG,'')='' ");
            if (dtTaskList.Rows.Count != 0)
            {
                DataRow[] dr = dtTaskList.Select("NC_TYPE like '%panel%'");//has panel data
                DataRow[] nodr = dtTaskList.Select("NC_TYPE not like '%panel%'");//no has data
                if (dr != null)
                {
                    NoAllocateInsert(dr);
                }
                if(nodr!=null)
                {
                    AllocateInsert(nodr);
                }

                InsertRecordList();
            }
        }
        /// <summary>
        /// no allocation for anyone and insert into record table
        /// </summary>
        /// <param name="dr"></param>
        private void NoAllocateInsert(DataRow[] dr)
        {
            foreach (DataRow d in dr)
            {
                IE_Part_RoutingInfo info = BaseFactory<IE_Part_Routing>.Instance.GetEntriyList(" 1=1 and PART_NO='"+d["PART_NO"].ToString() +"'").FirstOrDefault();
                if(info!=null)
                {
                    if(!string.IsNullOrEmpty(info.GROUP_CODE))
                    {
                        IE_Routing_CombinationInfo combinationInfo = BaseFactory<IE_Routing_Combination>.Instance.GetEntriyList("1=1 and GROUP_CODE='"+ info.GROUP_CODE + "'").FirstOrDefault();
                        if(combinationInfo!=null)
                        {
                            if (combinationInfo.ROUTING_CODE.ToLower().Contains("p05"))
                            {
                                //need to allocation for anyone into data collection
                                NC_Convert_ProcessRecordInfo recordInfo = new NC_Convert_ProcessRecordInfo();
                                recordInfo.PART_NO = d["PART_NO"].ToString();
                                recordInfo.PLANNING_START_TIME = DateTime.Now;
                                //if (d["IMPORT_TIME"].ToString() != "")
                                //    recordInfo.PLANNING_DONETIME = Convert.ToDateTime(d["IMPORT_TIME"].ToString());
                                //else
                                //    recordInfo.PLANNING_DONETIME = DateTime.Now;
                                recordInfo.IsRangmented = true;
                                recordInfo.DWG_NO = d["DWG_NO"].ToString();
                                lst.Add(recordInfo);
                            }
                            else
                            {
                                //no allocation and finshed insert into process record
                                NC_Convert_ProcessRecordInfo recordInfo = new NC_Convert_ProcessRecordInfo();
                                recordInfo.PART_NO = d["PART_NO"].ToString();
                                recordInfo.DWG_NO= d["DWG_NO"].ToString();
                                recordInfo.PLANNING_START_TIME = DateTime.Now;
                                recordInfo.PLANNING_ENGINEER = "admin";
                                //recordInfo.PLANNING_DONETIME = DateTime.Now;
                                recordInfo.CONVERTED_ENGINEER = "admin";
                                recordInfo.DWG_NO = d["DWG_NO"].ToString();
                                recordInfo.IsRangmented = true;
                                noLst.Add(recordInfo);

                            }
                        }
                        
                    }
                    
                }
            }
        }

        private void AllocateInsert(DataRow[] dr)
        {
            foreach (DataRow d in dr)
            {
                //need to allocation for anyone into data collection
                NC_Convert_ProcessRecordInfo recordInfo = new NC_Convert_ProcessRecordInfo();
                recordInfo.PART_NO = d["PART_NO"].ToString();
                //if (d["IMPORT_TIME"].ToString() != "")
                //    recordInfo.PLANNING_DONETIME = Convert.ToDateTime(d["IMPORT_TIME"].ToString());
                //else
                //    recordInfo.PLANNING_DONETIME = DateTime.Now;
                recordInfo.PLANNING_START_TIME = DateTime.Now;
                recordInfo.IsRangmented = true;
                recordInfo.DWG_NO = d["DWG_NO"].ToString();
                lst.Add(recordInfo);
            }
        }

        private void InsertRecordList()
        {
            List<NC_PN_StaffPlanInfo> staffList = BaseFactory<NC_PN_StaffPlan>.Instance.GetEntriyList(" 1=1 and Coefficient!=0");
           
            decimal sumRate = 0;
            int sumOrderList = 0;
            int sumOrderListAfter = 0;
            List<NC_PN_StaffPlanInfo> orderList = null;
            DateTime dtStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")+" 06:30:00");
            DateTime dtEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 13:30:00");

            sumRate = staffList.Sum(p=>p.Coefficient);
            sumOrderList = lst.Count();
            if (sumOrderList == 1)
            {
                int m = 0;
                foreach (NC_PN_StaffPlanInfo info in staffList)
                {
                    info.IsRand = m;
                    m++;
                }

                Random rdm = new Random();
                int iRandom = rdm.Next(m);
                
                NC_PN_StaffPlanInfo model = staffList.Where(p => p.IsRand == iRandom).FirstOrDefault();
                NC_Convert_ProcessRecordInfo rec = lst.FirstOrDefault();
                if (rec != null)
                {
                    rec.PLANNING_ENGINEER = model.UserName;
                    rec.PLANNING_START_TIME = DateTime.Now;
                    if (rec.PLANNING_START_TIME > dtStart&& rec.PLANNING_START_TIME < dtEnd)//in range of time set donetime else to set next day donetime
                        rec.PLANNING_DONETIME = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 16:00:00"); 
                    else
                        rec.PLANNING_DONETIME = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 12:00:00");
                    
                    BaseFactory<NC_Convert_ProcessRecord>.Instance.InsertKey(rec);

                    NC_Convert_TaskListInfo taskList = BaseFactory<NC_Convert_TaskList>.Instance.GetEntriyList(" 1=1 and PART_NO='" + rec.PART_NO + "'").FirstOrDefault();
                    if (taskList != null)
                    {
                        taskList.PLAN_FLAG = "1";
                        BaseFactory<NC_Convert_TaskList>.Instance.Update(taskList);
                    }


                }
            }
            else
            {

                foreach (NC_PN_StaffPlanInfo info in staffList)
                {
                    decimal count = Math.Ceiling(info.Coefficient * (Convert.ToDecimal(sumOrderList.ToString()) / sumRate));
                    info.Count = Convert.ToInt32(count.ToString());
                    //if(info!=null)
                    //{
                    //    DataTable dtUser = BaseBuildSql.GetDataTableBySql(" select*from Sys_MyUser  where Account='" + info.Account+"'");
                    //    if (dtUser.Rows.Count != 0)
                    //        info.Account = dtUser.Rows[0]["UserName"].ToString();
                    //}

                    sumOrderListAfter += info.Count;
                }
                //人员系统汇总表
                var disValue = (
                from c in staffList
                select c.Count)
                .Distinct();
                int iOverOrder = sumOrderListAfter - sumOrderList;
                if (disValue.Count() == 1)//from min List begin sub 1 until zero
                {
                    orderList = staffList.OrderBy(p => p.Coefficient).ToList(); ;
                    foreach (NC_PN_StaffPlanInfo info in orderList)
                    {
                        if (iOverOrder != 0)
                        {
                            info.Count = info.Count - 1;
                            iOverOrder--;
                        }
                    }
                }
                else //from max List begin sub 1 until zero
                {
                    orderList = staffList.OrderByDescending(p => p.Coefficient).ToList();
                    foreach (NC_PN_StaffPlanInfo info in orderList)
                    {
                        if (iOverOrder != 0)
                        {
                            info.Count = info.Count - 1;
                            iOverOrder--;
                        }
                    }
                }

                //begin insert All Arrangment Data have been finished  added Process Record
                foreach (NC_Convert_ProcessRecordInfo info in noLst)
                {
                    if (info != null)
                    {
                        info.PLANNING_START_TIME = DateTime.Now;
                        BaseFactory<NC_Convert_ProcessRecord>.Instance.InsertKey(info);
                    }
                }

                //begin insert all arrangment plan staff order Data to Process record

                foreach (NC_PN_StaffPlanInfo info in orderList)
                {
                    //List<NC_Convert_ProcessRecordInfo> arragmentList = lst.Where(p => p.IsRangmented = false).ToList();
                    for (int i = 0; i < info.Count; i++)
                    {
                        NC_Convert_ProcessRecordInfo rec = lst.FirstOrDefault();
                        if (rec != null)
                        {
                            rec.PLANNING_ENGINEER = info.UserName;
                            rec.PLANNING_START_TIME = DateTime.Now;
                            if (rec.PLANNING_START_TIME > dtStart && rec.PLANNING_START_TIME < dtEnd)
                                rec.PLANNING_DONETIME = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 16:00:00");
                            else
                                rec.PLANNING_DONETIME = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 12:00:00");
                            
                            BaseFactory<NC_Convert_ProcessRecord>.Instance.InsertKey(rec);

                            NC_Convert_TaskListInfo taskList = BaseFactory<NC_Convert_TaskList>.Instance.GetEntriyList(" 1=1 and PART_NO='"+ rec.PART_NO+ "'").FirstOrDefault();
                            if(taskList!=null)
                            {
                                taskList.PLAN_FLAG = "1";
                                BaseFactory<NC_Convert_TaskList>.Instance.Update(taskList);
                            }

                            lst.Remove(rec);

                        }
                    }
                }
            }
        }
        public override void DOStaffConfigure(IButtonInfo sender)
        {
            frmNC_StaffPlan frm = new frmNC_StaffPlan();
            frm.Show();
            base.DOStaffConfigure(sender);
        }

        private void gridControl1_EditorKeyPress(object sender, KeyPressEventArgs e)
        {
            
        }
        /// <summary>
        /// getting partno and creating directory and coping files
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridControl1_DoubleClick(object sender, EventArgs e)
        {
            string colName = gridView1.FocusedColumn.FieldName;
            if (gridView1.RowCount < 0) return;
            int iRow = gridView1.FocusedRowHandle;
            string partStatus = gridView1.GetRowCellValue(iRow, "部件编号").ToString();
            string nC_DK_SJ01 = "";
            string nC_DK_SJ02 = "";
            string partNo = gridView1.GetRowCellValue(iRow, "部件编号").ToString();
            string planNc = gridView1.GetRowCellValue(iRow, "计划转码").ToString();
            string modelNo = gridView1.GetRowCellValue(iRow, "模型编号").ToString();
            string dwgNo = gridView1.GetRowCellValue(iRow, "图纸号").ToString();
            string issueNo= gridView1.GetRowCellValue(iRow, "问题单号").ToString();

            string ncTargetPath = "";
            string ncSJRPath = "";
            string ncSummaryPath = "";
            string ncSJPath = "";
            string targetPath = "";
            string loadtTipPath = "";
            string pathFileName = "";
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + "\\PicturePathConfig.xml");
            XmlNode xn = doc.SelectSingleNode("Pictures");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                XmlElement xe = (XmlElement)xn1;
                XmlNodeList xn2 = xe.ChildNodes;
                foreach (XmlElement x2 in xn2)
                {
                    if (x2.Name == "NcTargetPath")
                        ncTargetPath = x2.InnerText;
                    if (x2.Name == "NcSJRPath")
                        ncSJRPath = x2.InnerText;
                    if (x2.Name == "NcSummaryPath")
                        ncSummaryPath = x2.InnerText;
                    if (x2.Name == "NcSJPath")
                        ncSJPath = x2.InnerText;
                    if (x2.Name == "NC_DK_SJ01")
                        nC_DK_SJ01 = x2.InnerText;
                    if (x2.Name == "NC_DK_SJ02")
                        nC_DK_SJ02 = x2.InnerText;
                }
            }

            string[] modelNos = modelNo.Split(':');
            string[] modelNoList = modelNos[1].Split(' ');
            string modelNoType = modelNoList[0].Trim() + "_" + modelNoList[1].Trim();

            targetPath = ncTargetPath + @"\" + partNo.Trim() + @"\";

            //pathFileName = partNo.Trim() + "_" + orderNo.Trim();
            pathFileName = partNo.Trim();
            string sourcePath = ncSJRPath + @"\" + modelNoType + @"\" + partNo;
            string prtPath = sourcePath + ".prt";
            string drwPath = sourcePath + ".drw";
            string tipPath = ncSummaryPath + @"\" + partNo + ".tif";
            //string targetPath = ncTargetPath + @"\" + partNo.Trim() + "_" + orderNo.Trim() + @"\";

            string singleTp1Asm = "tpl_prt_ref.asm";
            string singleTp1Drw = "tpl_prt_ref.drw";
            string doubleTp1Asm = "tpl_prt_ref_asm.asm";
            string doubleTp1Drw = "tpl_prt_ref_asm.drw";

            string singleTp1AsmPath = ncSJPath + @"\" + singleTp1Asm;
            string singleTp1DrwPath = ncSJPath + @"\" + singleTp1Drw;
            string doubleTp1AsmPath = ncSJPath + @"\" + doubleTp1Asm;
            string doubleTp1DrwPath = ncSJPath + @"\" + doubleTp1Drw;

            string prtTartgetPath = targetPath + partNo + ".prt";
            string drwTargetPath = targetPath + partNo + ".drw";
            string tipTartgetPath = targetPath + partNo + ".tif";
            loadtTipPath = tipTartgetPath;

            NC_Convert_ProcessRecordInfo bll = BaseFactory<NC_Convert_ProcessRecord>.Instance.GetEntriyList(" 1=1 and PART_NO='" + partNo + "'").FirstOrDefault();

            

            //just doubleclick specify column ca
            if (colName == "工艺状态")
            {



                if (gridView1.GetRowCellValue(iRow, "工艺状态").ToString() == "N")
                {

                    Lamex.mIE.UI.Frm_IE_Routing_Part frm = new Lamex.mIE.UI.Frm_IE_Routing_Part(dwgNo, "Laminate", partNo);
                    DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_Routing'");
                    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, frm, dt.Rows[0]["id"].ToString());
                    //frm.ShowDialog();
                    sbtnRefresh_Click(null, null);
                    return;
                }

            }
            if (colName == "部件编号")
            {
                if (gridView1.GetRowCellValue(iRow, "工艺状态").ToString() == "N")
                {
                    XtraMessageBox.Show("无工艺路线");
                    return;
                }
                if (gridView1.GetRowCellValue(iRow, "工艺状态").ToString() == "N") return;
                try
                {
                    //handle = IntPtr.Zero;
                    //handle = FindWindow(null, "Creo Parametric");
                    //if(handle==IntPtr.Zero)
                    //{
                    //    XtraMessageBox.Show("Creo没有启动！");
                    //    return;
                    //}
                    //if (gridView1.RowCount < 0) return;
                    //int iRow = gridView1.FocusedRowHandle;


                    //if (gridView1.GetRowCellValue(iRow, "工艺状态").ToString() == "N")
                    //{

                    //    Lamex.mIE.UI.Frm_IE_Routing_Part frm = new Lamex.mIE.UI.Frm_IE_Routing_Part(dwgNo, "Laminate", partNo);
                    //    DataTable dt = BaseBuildSql.GetDataTableBySql("select *　from　sys_menu where winformid='menuIE_Routing'");
                    //    MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, frm, dt.Rows[0]["id"].ToString());
                    //    frm.ShowDialog();
                    //    sbtnRefresh_Click(null, null);
                    //    return;
                    //}


                    string strLockUser = gridView1.GetRowCellValue(iRow, "锁定用户").ToString();
                    string convertDate = gridView1.GetRowCellValue(iRow, "转码完成").ToString();
                    string orderNo = gridView1.GetRowCellValue(iRow, "工作单号").ToString();
                    string NC_TYPE = gridView1.GetRowCellDisplayText(iRow, "转码类别").ToString();
                    DataTable dtRecord = BaseBuildSql.GetDataTableBySql(" select * from  NC_Convert_ProcessRecord where PART_NO='" + partNo + "'");
                    DataTable dtTask = BaseBuildSql.GetDataTableBySql(" select *from NC_Convert_TaskList where PART_NO='" + partNo + "'");

                    if (planNc != Lamex.Common.Loginer.CurrentUser.AccountName)
                    {
                        if (DialogResult.Yes != XtraMessageBox.Show("系统用户和计划转码人不是同一个人，是否要操作该单", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                            return;
                    }

                    if (dtRecord.Rows.Count != 0)
                    {
                        //NC状态
                        string strFinished = dtRecord.Rows[0]["CONVERTED_TIME"].ToString();
                        string strLocked = dtRecord.Rows[0]["LOCKED_TIME"].ToString();
                        string strNcStatus = dtRecord.Rows[0]["NC_STATE"].ToString().Trim();//NC状态
                        string strIssuse = dtRecord.Rows[0]["ISSUE_NO"].ToString();//问题
                        if (!string.IsNullOrEmpty(strLocked))
                        {
                            if (Loginer.CurrentUser.AccountName != dtRecord.Rows[0]["LOCKED_USER"].ToString())
                            {
                                XtraMessageBox.Show("该单被锁定！");
                                return;
                            }
                        }

                        if (strNcStatus.Trim() == "已转码")
                        {
                            if (DialogResult.Yes != XtraMessageBox.Show("转码已完成，是否需要再次进入？请确认！\r\n注：再次进入会清除当前转码时间及实际转码人，\r\n转码时间及实际转码人会依最后一次确认为准！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                            {
                                return;
                            }
                            //else
                            //{

                            //}
                        }
                        if (strNcStatus.Trim() == "审核中")
                        {
                            XtraMessageBox.Show("审核中，不能进行此操作！！");
                            return;
                        }
                        if (strNcStatus.Trim() == "已审核")
                        {
                            XtraMessageBox.Show("已审核，不能进行此操作！！");
                            return;
                        }
                        if (strNcStatus.Trim() == "待修改")
                        {
                            if (!string.IsNullOrEmpty(strIssuse))
                            {
                                DataTable dtIssue = BaseBuildSql.GetDataTableBySql(" select * from NC_Convert_IssueRecord where ISSUE_NO='" + strIssuse + "' and  ISSUE_FROM!='图纸更改' and RESPONSIBLE_DEPT!='NC'");
                                if (dtIssue.Rows.Count != 0)
                                {
                                    if (string.IsNullOrEmpty(dtIssue.Rows[0]["FINISHED_TIME"].ToString()))
                                    {
                                        XtraMessageBox.Show("问题待跟进，请确认完成后再转码！");
                                        return;
                                    }
                                }
                            }

                        }
                        if (strNcStatus.Trim() == "转码中")
                        {
                            if (strLockUser != Lamex.Common.Loginer.CurrentUser.AccountName)
                            {
                                XtraMessageBox.Show("此单转码中！");
                                return;
                            }
                        }
                        //if (!string.IsNullOrEmpty(strFinished))
                        //{
                        //    XtraMessageBox.Show("该单已经完成！");
                        //    return;
                        //}

                    }
                    if (dtTask.Rows.Count == 0)
                    {
                        XtraMessageBox.Show("NC任务表没该单数据！");
                        return;
                    }
                    //if (!string.IsNullOrEmpty(convertDate))
                    //{
                    //    XtraMessageBox.Show("该图纸已完成，无法再操作！");
                    //    return;
                    //}
                    modelNo = modelNo.Split(':')[1];
                    if (string.IsNullOrEmpty(partNo))
                    {
                        XtraMessageBox.Show("部件编号为空！");
                        return;
                    }
                    //compare planStaff and currently loginer UseName
                    //if the same create the directory else tip warning

                    // follow getting all filepath 



                    //打开窗体，并将部件编号、部件描述、木纹方向、部件厚度传递过去
                    switch (NC_TYPE)
                    {
                        case "DESK_SJR":
                            {

                                #region""

                                if (dtRecord.Rows[0]["NC_STATE"].ToString().Trim() == "改图纸" || dtRecord.Rows[0]["NC_STATE"].ToString().Trim() == "")
                                {
                                    if (!Directory.Exists(targetPath))
                                        Directory.CreateDirectory(targetPath);
                                    #region"区分开"


                                    if (!File.Exists(prtPath))
                                    {
                                        XtraMessageBox.Show("不存在图纸：" + prtPath);
                                        return;
                                    }
                                    if (!File.Exists(drwPath))
                                    {
                                        XtraMessageBox.Show("不存在图纸：" + drwPath);
                                        return;
                                    }
                                    if (!File.Exists(tipPath))
                                    {
                                        XtraMessageBox.Show("不存在图纸：" + tipPath);
                                        return;
                                    }
                                    if (!File.Exists(singleTp1AsmPath))
                                    {
                                        XtraMessageBox.Show("不存在图纸：" + singleTp1AsmPath);
                                        return;
                                    }
                                    if (!File.Exists(singleTp1DrwPath))
                                    {
                                        XtraMessageBox.Show("不存在图纸：" + singleTp1DrwPath);
                                        return;
                                    }

                                    //checking NC_Convert_TaskList if it  is  single else double
                                    if (dtTask.Rows[0]["DOUBLE_CUT_SIZE"].ToString() == "NULL" || dtTask.Rows[0]["DOUBLE_CUT_SIZE"].ToString().Trim() == "")
                                    {
                                        //single copy two files
                                        //if not ,create an new directory
                                        if (!Directory.Exists(targetPath))
                                        {
                                            Directory.CreateDirectory(targetPath);
                                        }

                                        if (File.Exists(prtTartgetPath))
                                            File.Delete(prtTartgetPath);
                                        if (File.Exists(drwTargetPath))
                                            File.Delete(drwTargetPath);
                                        if (File.Exists(tipTartgetPath))
                                            File.Delete(tipTartgetPath);
                                        File.Copy(prtPath, prtTartgetPath);
                                        File.Copy(drwPath, drwTargetPath);
                                        File.Copy(tipPath, tipTartgetPath);

                                        string sigleAsmTargetPath = targetPath + singleTp1Asm;
                                        string sigledrwTargetPath = targetPath + partNo + "_SNG.drw";
                                        if (File.Exists(sigleAsmTargetPath))
                                            File.Delete(sigleAsmTargetPath);
                                        if (File.Exists(sigledrwTargetPath))
                                            File.Delete(sigledrwTargetPath);
                                        File.Copy(singleTp1AsmPath, sigleAsmTargetPath);
                                        File.Copy(singleTp1DrwPath, sigledrwTargetPath);
                                    }
                                    else
                                    {

                                        if (!File.Exists(doubleTp1AsmPath))
                                        {
                                            XtraMessageBox.Show("文件不存在：" + doubleTp1AsmPath);
                                            return;
                                        }
                                        if (!File.Exists(doubleTp1DrwPath))
                                        {
                                            XtraMessageBox.Show("文件不存在：" + doubleTp1DrwPath);
                                            return;
                                        }
                                        //if not ,create an new directory
                                        if (!Directory.Exists(targetPath))
                                        {
                                            Directory.CreateDirectory(targetPath);
                                        }
                                        prtTartgetPath = targetPath + partNo + ".prt";
                                        drwTargetPath = targetPath + partNo + ".drw";
                                        tipTartgetPath = targetPath + partNo + ".tif";
                                        loadtTipPath = tipTartgetPath;
                                        if (File.Exists(prtTartgetPath))
                                            File.Delete(prtTartgetPath);
                                        if (File.Exists(drwTargetPath))
                                            File.Delete(drwTargetPath);
                                        if (File.Exists(tipTartgetPath))
                                            File.Delete(tipTartgetPath);
                                        File.Copy(prtPath, prtTartgetPath);
                                        File.Copy(drwPath, drwTargetPath);
                                        File.Copy(tipPath, tipTartgetPath);

                                        string sigleAsmTargetPath = targetPath + singleTp1Asm;
                                        //string sigledrwTargetPath = targetPath  +"N" +partNo + ".drw"; 
                                        string sigledrwTargetPath = targetPath + partNo + "_SNG.drw";
                                        string doubleAsmTargetPath = targetPath + doubleTp1Asm;
                                        //string doubleDrwTargetPath = targetPath +"N" + partNo + "_asm.drw"; 
                                        string doubleDrwTargetPath = targetPath + partNo + "_DBL.drw";

                                        if (File.Exists(sigleAsmTargetPath))
                                            File.Delete(sigleAsmTargetPath);
                                        if (File.Exists(sigledrwTargetPath))
                                            File.Delete(sigledrwTargetPath);
                                        if (File.Exists(doubleAsmTargetPath))
                                            File.Delete(doubleAsmTargetPath);
                                        if (File.Exists(doubleDrwTargetPath))
                                            File.Delete(doubleDrwTargetPath);

                                        File.Copy(singleTp1AsmPath, sigleAsmTargetPath);
                                        File.Copy(singleTp1DrwPath, sigledrwTargetPath);
                                        File.Copy(doubleTp1AsmPath, doubleAsmTargetPath);
                                        File.Copy(doubleTp1DrwPath, doubleDrwTargetPath);
                                    }

                                    //if (bll != null)
                                    //{
                                    //    bll.CONVERTED_TIME = null;
                                    //    bll.CONVERTED_ENGINEER = null;
                                    //    bll.NC_STATE = "转码中";
                                    //    bll.LOCKED_TIME = DateTime.Now;
                                    //    bll.LOCKED_USER = Loginer.CurrentUser.AccountName;
                                    //    BaseFactory<NC_Convert_ProcessRecord>.Instance.Update(bll);
                                    //}
                                    //gridView1.SetRowCellValue(iRow, "NC状态", "转码中");


                                    #endregion



                                }

                                if (!Directory.Exists(targetPath))
                                {
                                    string movePath = nC_DK_SJ01 + @"\" + partNo;
                                    DirectoryInfo di = new DirectoryInfo(movePath);//移动文件
                                    di.MoveTo(ncTargetPath + @"\" + partNo);
                                }
                                if (bll != null)
                                {
                                    bll.CONVERTED_TIME = null;
                                    bll.CONVERTED_ENGINEER = null;
                                    bll.LOCKED_TIME = DateTime.Now;
                                    bll.LOCKED_USER = Loginer.CurrentUser.AccountName;
                                    //bll.PLANNING_DONETIME = DateTime.Now;
                                    bll.NC_STATE = "转码中";
                                    gridView1.SetRowCellValue(iRow, "锁定用户", Loginer.CurrentUser.AccountName);
                                    gridView1.SetRowCellValue(iRow, "NC状态", "转码中");
                                    gridView1.SetRowCellValue(iRow, "计划完成", DateTime.Now);

                                    BaseFactory<NC_Convert_ProcessRecord>.Instance.Update(bll);


                                }

                                #endregion
                                string dkProcessName = typeof(frmNC_Convert_DKSJR_Processing).ToString();
                                Form childProcess = MdiTools.ActiveChildWebBrowse((this.MdiParent as IMdiForm) as Form, dkProcessName);
                                if (childProcess == null)
                                    MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmNC_Convert_DKSJR_Processing(partNo, targetPath, loadtTipPath, pathFileName), sender as ToolStripMenuItem);
                                else
                                {
                                    if (childProcess != null)
                                    {
                                        frmNC_Convert_DKSJR_Processing frm = childProcess as frmNC_Convert_DKSJR_Processing;
                                        frm.InitLoad(partNo, targetPath, loadtTipPath, pathFileName);
                                        frm.Show();
                                    }
                                }
                                //form1.DoView(null);
                            }
                            break;
                        case "DESK_STD":
                            frmNC_Convert_DKSTD_Processing form2 = new frmNC_Convert_DKSTD_Processing();
                            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form2, "menuNC_Convert_Processing_DKstd");
                            form2.DoView(null);
                            break;
                        case "PANEL_SJR":
                            frmNC_Convert_PN_AL_SJR form3 = new frmNC_Convert_PN_AL_SJR();
                            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form3, "frmNC_Convert_PNAL_SJR");
                            form3.DoView(null);
                            break;
                        case "PANEL_STD":
                            frmNC_Convert_PN_AL_STD form4 = new frmNC_Convert_PN_AL_STD();
                            MdiTools.OpenChildForm_Param(this.MdiParent as IMdiForm, form4, "frmNC_Convert_PNAL_STD");
                            form4.DoView(null);
                            break;
                        default:
                            break;
                    }


                    //string dkProcessName = typeof(frmNC_Convert_DKSJR_Processing).ToString();
                    //Form childProcess = MdiTools.ActiveChildWebBrowse((this.MdiParent as IMdiForm) as Form, dkProcessName);
                    //if(childProcess == null)
                    //MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmNC_Convert_DKSJR_Processing(partNo), sender as ToolStripMenuItem);
                    //else
                    //{
                    //    if (childProcess != null)
                    //    { 
                    //        frmNC_Convert_DKSJR_Processing  frm = childProcess as frmNC_Convert_DKSJR_Processing;
                    //        frm.InitLoad(partNo);
                    //        frm.Show();
                    //    }
                    //}
                    //string dkCheckingName = typeof(frmNC_Convert_DKSJR_Checking).ToString();
                    //Form childCheck = MdiTools.ActiveChildWebBrowse((this.MdiParent as IMdiForm) as Form, dkCheckingName);
                    //if (childCheck == null)
                    //    MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmNC_Convert_DKSJR_Checking(), sender as ToolStripMenuItem);
                    //else
                    //{
                    //    //if (childProcess != null)
                    //    //{
                    //    //    frmNC_Convert_DKSJR_Checking frm = childProcess as frmNC_Convert_DKSJR_Checking;
                    //    //    //frm.InitLoad(partNo);
                    //    //    //frm.Show();
                    //    //}
                    //}

                    //System.IO.Directory.SetAccessControl(ncTargetPath, DirectorySecurity);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }

            if (colName == "转码完成")
            {
                DataTable dtRecord = BaseBuildSql.GetDataTableBySql(" select * from  NC_Convert_ProcessRecord where PART_NO='" + partNo + "'");
                string strFinished = dtRecord.Rows[0]["CONVERTED_TIME"].ToString();
                string strLocked = dtRecord.Rows[0]["LOCKED_TIME"].ToString();
                string strNcStatus = dtRecord.Rows[0]["NC_STATE"].ToString().Trim();//NC状态
                string strIssuse = dtRecord.Rows[0]["ISSUE_NO"].ToString();//问题
                if (!string.IsNullOrEmpty(strLocked))
                {
                    if (Loginer.CurrentUser.AccountName != dtRecord.Rows[0]["LOCKED_USER"].ToString())
                    {
                        XtraMessageBox.Show("该单被锁定！");
                        return;
                    }
                }
                if (!(dtRecord.Rows[0]["NC_STATE"].ToString().Trim() == "已转码"|| dtRecord.Rows[0]["NC_STATE"].ToString().Trim() == "审核中"))
                {
                    XtraMessageBox.Show("不是已转码或审核中，不能进操作");
                    return;
                }
                string ncTipPath= nC_DK_SJ01+  @"\" + partNo + @"\" + partNo + ".tif";
                string ncConvertedPath = nC_DK_SJ01 + @"\" + partNo;
                if (bll != null)
                {
                    
                    bll.NC_STATE = "审核中";
                    bll.LOCKED_TIME = DateTime.Now;
                    bll.LOCKED_USER = Loginer.CurrentUser.AccountName;
                    gridView1.SetRowCellValue(iRow, "NC状态", "审核中");
                    //gridView1.SetRowCellValue(iRow, "审核完成", DateTime.Now);
                    gridView1.SetRowCellValue(iRow, "锁定用户", Loginer.CurrentUser.AccountName);
                    BaseFactory<NC_Convert_ProcessRecord>.Instance.Update(bll);


                }
                
                string dkProcessName = typeof(frmNC_Convert_DKSJR_Processing).ToString();
                Form childProcess = MdiTools.ActiveChildWebBrowse((this.MdiParent as IMdiForm) as Form, dkProcessName);
                if (childProcess == null)
                    MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmNC_Convert_DKSJR_Processing(partNo, ncConvertedPath, ncTipPath, pathFileName), sender as ToolStripMenuItem);
                else
                {
                    if (childProcess != null)
                    {
                        frmNC_Convert_DKSJR_Processing frm = childProcess as frmNC_Convert_DKSJR_Processing;
                        frm.InitLoad(partNo, ncConvertedPath, ncTipPath, pathFileName);
                        frm.Show();
                    }
                }

            }

            if (colName == "问题单号")
            {
                string dkProcessName = typeof(frmNC_Completed_Register).ToString();
                Form childProcess = MdiTools.ActiveChildWebBrowse((this.MdiParent as IMdiForm) as Form, dkProcessName);
                if (childProcess == null)
                    MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmNC_Completed_Register(issueNo), sender as ToolStripMenuItem);
                else
                {

                    if (childProcess != null)
                    {
                        frmNC_Completed_Register frm = childProcess as frmNC_Completed_Register;
                        frm.issueNo = issueNo;
                        frm.Show();
                    }
                }

            }
        }

        public static Form IsActiveForm(Form mdiParent, string formTypeName)
        {
            for (int x = 0; x < mdiParent.MdiChildren.Length; x++)
            {
                string ss = mdiParent.MdiChildren[x].GetType().ToString().ToUpper();
                if (ss == formTypeName.ToUpper())
                {
                    IMdiChildForm child = mdiParent.MdiChildren[x] as IMdiChildForm;
                    if (child.AllowMultiInstatnce) continue;
                    mdiParent.MdiChildren[x].Activate();
                    return mdiParent.MdiChildren[x];
                }
            }
            return null;
        }

        private void btn_UnLock_Click(object sender, EventArgs e)
        {
           
            
        }

        public override void DoUnLocked(IButtonInfo sender)
        {
            if (gridView1.RowCount > 0)
            {
                int iRow = gridView1.FocusedRowHandle;
                string partNo = gridView1.GetRowCellValue(iRow, "部件编号").ToString();
                string strNcStatus = gridView1.GetRowCellValue(iRow, "NC状态").ToString(); ;//NC状态
                NC_Convert_ProcessRecordInfo bll = BaseFactory<NC_Convert_ProcessRecord>.Instance.GetEntriyList(" 1=1 and PART_NO='" + partNo + "'").FirstOrDefault();
                if (bll != null)
                {
                    bll.LOCKED_TIME = null;
                    bll.LOCKED_USER = null;
                    if (strNcStatus == "转码中")
                        bll.NC_STATE = null;
                    else if (strNcStatus == "审核中")
                        bll.NC_STATE = "已转码";

                    if (BaseFactory<NC_Convert_ProcessRecord>.Instance.Update(bll))
                    {
                        
                        gridView1.SetRowCellValue(iRow, "锁定用户", "");
                        if (strNcStatus == "转码中")
                            gridView1.SetRowCellValue(iRow, "NC状态", "");
                        else if (strNcStatus == "审核中")
                            gridView1.SetRowCellValue(iRow, "NC状态", "已转码");

                        //需要解除文件权限
                        XtraMessageBox.Show("成功解锁！");
                        return;
                    }
                    else
                    {
                        XtraMessageBox.Show("解锁失败！");
                        return;
                    }


                }
            }
            base.DoUnLocked(sender);
        }

        private void panelControl2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void chkHide_CheckedChanged(object sender, EventArgs e)
        {
            DoView(null);
        }
    }
}